﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataBase;

public partial class bl_Article : System.Web.UI.Page, ICallbackEventHandler
{
    long ArticleId;
    string callBackData = String.Empty;
    BlogAdapter ba = new BlogAdapter();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (long.TryParse(Request.QueryString["id"], out ArticleId))
        {
            Article article = ba.GetArticleWithComments(ArticleId);

            if (article == null)
                Response.Redirect("~/errors/articlenotfound.aspx");

            var list = ba.GetArticles(null, null);
            var length = list.Count;
            var currIndex = list.FindIndex(a => a.ArticleID == article.ArticleID);
            var next = (currIndex + 1) % length;
            var prev = (currIndex + length - 1) % length;
            var prevArt = list[prev];
            var nextArt = list[next];
            prevArticle.HRef = "article.aspx?title=" + prevArt.Title + "&id=" + prevArt.ArticleID;
            nextArticle.HRef = "article.aspx?title=" + nextArt.Title + "&id=" + nextArt.ArticleID;
            prevArticle.InnerText = prevArt.Title;
            nextArticle.InnerText = nextArt.Title;

            CommentsPlaceHolder.Visible = article.AllowComments != false;
            DateMonth.Text = article.CreateDate.ToString("MMM");
            DateDay.Text = article.CreateDate.Day.ToString();
            PostTitle.InnerText = article.Title;

            /*
             * 
             * <small>Posted in 
                  <a rel="category tag" title="View all posts in Events" href="#">Events</a>
                , <a rel="category tag" title="View all posts in Media Gallery" href="#">Media Gallery</a>
                , <a rel="category tag" title="View all posts in Peach Press" href="#">Peach Press</a>
                , <a rel="category tag" title="View all posts in Uncategorized" href="#">Uncategorized</a>
                by <b>ton</b> 
               </small>
             */


            PostTags.Text = "<small>Posted in ";
            foreach (var tg in article.Tags)
            {
                PostTags.Text += "<a rel=\"category tag\" title=\"View all posts in " + tg.TagName + "\" href=\"" + Master.Root + "default.aspx?category=" + tg.TagName + "\">" + tg.TagName + ", </a>";
            }
            PostTags.Text += "by <b>" + article.Author + "</b> </small>";

            posttext.InnerHtml = article.ArticleText;
            authorp.InnerText = "-" + article.Author + "-";

            Comments.Text = GetCommentsHtml(article);

            #region callback scripts
            ClientScriptManager cm = Page.ClientScript;
            String cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
            String callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";
            cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            #endregion
        }
        else
        {
            Response.Redirect("~/");
        }
    }

    private string GetCommentsHtml(Article article)
    {
        string retValue = "";
        if (article.Comments.Count > 0)
        {
            retValue = "<h3 id=\"comments\">" + article.Comments.Count + " Responses</h3>";
            retValue += "<ol id=\"comms\" class=\"commentlist\">";
            bool odd = false;
            foreach (var comment in article.Comments)
            {
                retValue +=
                    "<li id=\"comment-" + comment.CommentID + "\" class=\"" + (odd ? "" : "alt") + "\"><b>" + comment.Author + "</b> &nbsp; Writes:<br />" +
                            "<small class=\"commentmetadata\"><a href=\"#comment-" + comment.CommentID + "\">" + comment.CreateDate + "</a> </small>" +
                            "<p>" + comment.CommentText + "</p>" +
                        "</li>";
                odd = !odd;
            }
            retValue += "</ol>";
        }
        return retValue;
    }

    string ICallbackEventHandler.GetCallbackResult()
    {
        return callBackData;
    }

    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
    {
        if (String.IsNullOrEmpty(eventArgument))
        {
            callBackData = "Error|დაფიქსირდა შეცდომა";
            return;
        }
        var parts = eventArgument.Split('|');
        switch (parts[0])
        {
            case "Add Comment": ////// "Add Comment|" + author + "|" + text + "|" + "7";
                {
                    try
                    {
                        string author = parts[1];
                        string text = parts[2];
                        int count = int.Parse(parts[3]);
                        var id = ba.CommentCreateUpdate(null, ArticleId, author, text);
                        if (id > 0)
                        {
                            callBackData = "Success|" +
                                "<li id=\"comment-" + id + "\" class=\"addedd " + (count % 2 == 1 ? "" : "alt") + "\">" +
                                "<b>" + author + "</b>" +
                                " Writes:<br>" +
                                "<small class=\"commentmetadata\">" +
                                    "<a href=\"#comment-" + id + "\" >" + DateTime.Now.ToString() + "</a>" +
                                "</small>" +
                                "<p>" + text + "</p>" +
                                "</li>";
                        }
                        else
                        {
                            callBackData = "Error|დაფიქსირდა შეცდომა და კომენტარი არ დაემატა";
                        }
                    }
                    catch (Exception ex)
                    {
                        callBackData = "Error|დაფიქსირდა შეცდომა და კომენტარი არ დაემატა";
                    }
                    break;
                }
            case "":
                {
                    break;
                }
            case "S":
                {
                    break;
                }
            default:
                {
                    break;
                }
        }
    }
}